Skip to main content

Lab 29: Delete Backup from S3 Using Terraform

The Nautilus DevOps team is currently engaged in a cleanup process, focusing on removing unnecessary data and services from their AWS account. As part of the migration process, several resources were created for one-time use only, necessitating a cleanup effort to optimize their AWS environment.

A S3 bucket named datacenter-bck-21065 already exists.

  1. Copy the contents of datacenter-bck-21065 S3 bucket to /opt/s3-backup/ directory on terraform-client host (the landing host once you load this lab).

  2. Delete the S3 bucket datacenter-bck-21065.

  3. Use the AWS CLI through Terraform to accomplish this task—for example, by running AWS CLI commands within Terraform. The Terraform working directory is /home/bob/terraform. Update the main.tf file (do not create a separate .tf file) to accomplish this task.

Note: Right-click under the EXPLORER section in VS Code and select Open in Integrated Terminal to launch the terminal.

Update main.tf

# /home/bob/terraform/main.tf

resource "null_resource" "s3_backup_and_cleanup" {
# This resource will execute the provisioners in the order they are defined.

# 1. Copy the contents of datacenter-bck-21065 S3 bucket
# to /opt/s3-backup/ directory on terraform-client host.
provisioner "local-exec" {
command = "mkdir -p /opt/s3-backup/ && aws s3 sync s3://datacenter-bck-21065 /opt/s3-backup/"
}

# 2. Delete the S3 bucket datacenter-bck-21065.
# The 'rb' (remove bucket) command with '--force' will recursively delete
# all objects in the bucket first, then delete the bucket itself.
provisioner "local-exec" {
command = "aws s3 rb s3://datacenter-bck-21065 --force"
}
}
terraform init
terraform plan -out kke.plan && terraform apply kke.plan
# or apply forcefully without creating plan and applying it
terraform apply -auto-approve


# aws cli
aws secretsmanager get-secret-value --secret-id datacenter-secret --query SecretString